//
//  GroupMemberModel.swift
//  LocationTrackerAdmin
//
//  Created by mac on 2025/2/25.
//
import Vapor
import Fluent
import SQLKit
import Vapor
import Fluent

final class GroupMemberModel: Model, Content {
    static var schema: String {
        return "group_members"
    }
    
    @ID(custom: FieldKeys.id)
    var id: String?
    
    @Parent(key: FieldKeys.groupID)
    var group: GroupModel
    
    @Field(key: FieldKeys.memberID)
    var memberID: String
    
    @Field(key: FieldKeys.joinDate)
    var joinDate: Date
    
    @Field(key: FieldKeys.joinCode)
    var joinCode: String
    
    @Field(key: FieldKeys.current)
    var current: Bool
    init() { }
    
    init(id: String? = nil, groupID: String, memberID: String, joinDate: Date, joinCode: String, current: Bool = false) {
        self.id = id
        self.$group.id = groupID
        self.memberID = memberID
        self.joinDate = joinDate
        self.joinCode = joinCode
        self.current = current
    }
}

extension GroupMemberModel {
    struct FieldKeys {
        static var id: FieldKey { "group_member_id" }
        static var groupID: FieldKey { "group_member_group_id" }
        static var memberID: FieldKey { "group_member_member_id" }
        static var joinDate: FieldKey { "group_member_join_date" }
        static var joinCode: FieldKey { "group_member_join_code" }
        static var current: FieldKey { "group_member_current" }
    }
}

struct GroupMemberModelMigration: AsyncMigration {
    func prepare(on database: Database) async throws {
        try await database.schema(GroupMemberModel.schema)
            .field(GroupMemberModel.FieldKeys.id, .string, .custom("COMMENT '记录ID'"))
            .field(GroupMemberModel.FieldKeys.groupID, .string, .required, .custom("COMMENT '群组ID'"))
            .field(GroupMemberModel.FieldKeys.memberID, .string, .required, .custom("COMMENT '成员ID'"))
            .field(GroupMemberModel.FieldKeys.joinDate, .custom("datetime(0)"), .required, .custom("COMMENT '加入日期'"))
            .field(GroupMemberModel.FieldKeys.joinCode, .string, .required, .custom("COMMENT '邀请码'"))
            .field(GroupMemberModel.FieldKeys.current, .bool, .required, .custom("COMMENT '群组是否是该用户当前选定的群组'"))
            .create()
    }
    
    func revert(on database: Database) async throws {
        try await database.schema(GroupMemberModel.schema).delete()
    }
}
